package io.gitee.kotle.player.activity

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.media3.common.MediaItem
import io.gitee.kotle.player.R
import io.gitee.kotle.player.download.IPlayerDownload

/**
 * 显示下载列表
 */
class PlayerDownloadActivity : Activity() {

    private val downloader by lazy {
        IPlayerDownload.exoPlayerDownload(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_player_download)
        val rcv = findViewById<RecyclerView>(R.id.rcv)
        rcv.layoutManager = LinearLayoutManager(this)
        downloader.resumeDownloads()
        downloader.getAllDownloads {
            val adapter = Adapter(downloader, it)
            rcv.adapter = adapter
            downloader.addListener(Pair(null, object : IPlayerDownload.IListener<MediaItem> {
                override suspend fun onDownload(downloadInfo: IPlayerDownload.DownloadInfo<MediaItem>) {
                    it.toList().forEachIndexed { index, old ->
                        if (old.mediaId == downloadInfo.mediaId && old.state != downloadInfo.state) {
                            if (downloadInfo.state == IPlayerDownload.State.Removed) {
                                it.removeAt(index)
                                adapter.notifyItemRemoved(index)
                                Toast.makeText(
                                    this@PlayerDownloadActivity,
                                    "删除成功",
                                    Toast.LENGTH_SHORT
                                ).show()
                            } else {
                                it[index] = downloadInfo
                                adapter.notifyItemChanged(index)
                            }
                        }
                    }
                }
            }))
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        downloader.release()
    }

    private class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvName = itemView.findViewById<TextView>(R.id.tvName)
        val tvState = itemView.findViewById<TextView>(R.id.tvState)
    }

    private class Adapter(
        private val downloader: IPlayerDownload<MediaItem>,
        private val infoList: MutableList<IPlayerDownload.DownloadInfo<MediaItem>>
    ) :
        RecyclerView.Adapter<Holder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
            return Holder(
                LayoutInflater.from(parent.context).inflate(
                    R.layout.holder_player_download,
                    parent,
                    false
                )
            )
        }

        override fun getItemCount(): Int = infoList.count()

        override fun onBindViewHolder(holder: Holder, position: Int) {
            val data = infoList[position]
            val extra = data.extra
            holder.tvName.text = if (extra != null) String(extra) else null
            holder.tvState.text = when (data.state) {
                IPlayerDownload.State.Completed -> "完成"
                IPlayerDownload.State.Downloading -> "下载中"
                IPlayerDownload.State.Failed -> "失败"
                IPlayerDownload.State.Queued -> "队列中"
                IPlayerDownload.State.Removing -> "删除中"
                IPlayerDownload.State.Restarting -> "重试中"
                IPlayerDownload.State.Stopped -> "停止"
                IPlayerDownload.State.Removed -> "已删除"
            }
            holder.itemView.setOnClickListener {
                val mediaId = data.media.localConfiguration?.uri?.toString() ?: data.media.mediaId
                PlayerActivity.start(it.context, mediaId, title = holder.tvName.text.toString())
            }
            holder.itemView.setOnLongClickListener {
                AlertDialog.Builder(it.context)
                    .setTitle("提示")
                    .setMessage("删除《${holder.tvName.text}》？")
                    .setCancelable(false)
                    .setPositiveButton("取消") { d, i ->
                        d.dismiss()
                    }
                    .setNegativeButton("删除") { d, i ->
                        d.dismiss()
                        downloader.removeDownload(data.mediaId)
                    }
                    .show()
                true
            }
        }
    }
}